package mp3tagger.controller;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import mp3model.Mp3Model;
import mp3tagger.Activator;
import mp3tagger.ids.Mp3TaggerIds;

import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;

public class Mp3ListController extends PlatformObject implements ISelectionListener {

	private List<Mp3Model> mp3List;
	private int currentIndex = -1;
	protected transient PropertyChangeSupport listeners = new PropertyChangeSupport(this);
	
	public void addPropertyChangeListener( PropertyChangeListener l) {
		if (l == null)
			throw new IllegalArgumentException();
		this.listeners.addPropertyChangeListener( l);
	}
	
	protected void firePropertyChanged(String property, Object oldValue, Object newValue) {
		if ( this.listeners.hasListeners(property))
			this.listeners.firePropertyChange(property, oldValue, newValue);
	}
	
	public void loadList(String folderPath) {
		loadList(new File(folderPath));
	}
	
	public void loadList(File folder) {
		if (!folder.exists() || !folder.isDirectory())
			return;
		
		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".mp3");
			}
		};
		
		if (mp3List == null)
			mp3List = new ArrayList<Mp3Model>();
		for (File file : folder.listFiles(filter)) {
			mp3List.add( new Mp3Model(file));
		}
		firePropertyChanged(Mp3TaggerIds.ITEMS_LOADED, null, mp3List);
	}

	public void setSourceFolder(String path) {
		loadList(path);
	}


	private void updateCurrent() {
		firePropertyChanged(Mp3TaggerIds.CURRENT_MP3, null, mp3List.get(currentIndex));
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		if (selection != null && mp3List != null && mp3List.size() > 0 && selection instanceof IStructuredSelection) {
			Mp3Model mp3 = (Mp3Model) ((IStructuredSelection)selection).getFirstElement();
			for (int i = 0; i < mp3List.size(); i++) {
				if ( mp3.equals( mp3List.get(i))) {
					if ( i >= mp3List.size()-1)
						currentIndex = mp3List.size()-1;
					else
						currentIndex = i;
					break;
				}
			}
			updateCurrent();
		}
	}

	public void previous() {
		if ( mp3List != null) {
			if (currentIndex > 0) {
				currentIndex--;
				updateCurrent();
			}
		}
	}
	
	public void next() {
		if ( mp3List != null) {
			if (currentIndex < mp3List.size()-1) {
				currentIndex++;
				updateCurrent();
			}
		}
	}
	
}
